//
//  GoodLineViewController.m
//  Logistics
//
//  Created by 华谕 on 2017/11/3.
//  Copyright © 2017年 HUYU. All rights reserved.
//

#import "GoodLineViewController.h"
#import "JSAddressPickerView.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@interface GoodLineViewController ()<UIScrollViewDelegate,UITextFieldDelegate,JSAddressPickerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
{
    UIView *publicView;
    UIScrollView *scrollview;
    UITextField *nameField;
    UITextField *addressField;
    UITextField *phoneField;
    UILabel *areaLab;
    UIButton *submitBtn;
    UIView *companyView;
    UILabel *rzTypeLab;
    UITextField *companyField;
    UIView *bottomView;
    UIImageView *leftImgView;
    UIImageView *rightImgView;
    
}
@property (nonatomic, strong) JSAddressPickerView *pickerView;
@property (nonatomic, assign)NSInteger phoneType;
@property (nonatomic, strong)UIImage *leftImg;
@property (nonatomic, strong)UIImage *rightImg;
@end

@implementation GoodLineViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpanhuishou:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
}

- (void)creatUI
{
    self.view.backgroundColor = RGB(245, 245, 245);
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"推荐优质专线";
    scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT)];
    scrollview.backgroundColor = RGB(245, 245, 245);
    scrollview.delegate = self;
    scrollview.contentOffset = CGPointMake(0, 0);
    scrollview.pagingEnabled = NO;
    [self.view addSubview:scrollview];
    companyView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 110*displayheight)];
    companyView.backgroundColor = [UIColor clearColor];
    [scrollview addSubview:companyView];
    NSArray *imgarray = @[@"my_icon01",@"my_icon02"];
    for (int k = 0; k < 2; k++)
    {
        UIView *backView1 = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 10*displayheight+k*55*displayheight, SCREEN_WIDTH-30*displaywidth, 45*displayheight)];
        backView1.backgroundColor = [UIColor whiteColor];
        [scrollview addSubview:backView1];
        UIImageView *imageview = [ZCControl createImageViewWithFrame:CGRectMake(5*displaywidth, 12.5*displayheight, 20*displaywidth, 20*displayheight) ImageName:imgarray[k]];
        imageview.contentMode = UIViewContentModeScaleAspectFit;
        [backView1 addSubview:imageview];
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(35*displaywidth, 12.5*displayheight, 1, 20*displayheight)];
        line1.backgroundColor = RGB(204, 204, 204);
        [backView1 addSubview:line1];
        if (k == 0)
        {
            rzTypeLab = [ZCControl createLabelWithFrame:CGRectMake(40*displaywidth, 0, SCREEN_WIDTH-100*displaywidth, 45*displayheight) Font:15.0 Text:@"汽运专线" Color:RGB(135, 135, 135)];
            [backView1 addSubview:rzTypeLab];
        }
        else
        {
            UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(40*displaywidth, 2.5*displayheight, SCREEN_WIDTH-70*displaywidth, 40*displayheight) placeholder:@"公司名称" passWord:NO leftImageView:nil rightImageView:nil Font:15.0];
            [textfield setValue:RGB(135, 135, 135) forKeyPath:@"_placeholderLabel.textColor"];
            textfield.delegate = self;
            textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
            textfield.textColor = RGB(48, 48, 48);
            textfield.textAlignment = NSTextAlignmentLeft;
            [backView1 addSubview:textfield];
            companyField = textfield;
        }
    }
    publicView = [[UIView alloc] initWithFrame:CGRectMake(0, 110*displayheight, SCREEN_WIDTH, 230*displayheight)];
    publicView.backgroundColor = [UIColor clearColor];
    [scrollview addSubview:publicView];
    NSArray *imgAry = @[@"my_icon03",@"",@"",@"my_icon04"];
    NSArray *pladerAry = @[@"姓名",@"",@"输入详细地址",@"手机号"];
    for (int i = 0; i < pladerAry.count; i ++)
    {
        if (i != 1)
        {
            UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 10*displayheight+i*55*displayheight, SCREEN_WIDTH-30*displaywidth, 45*displayheight)];
            backView.backgroundColor = [UIColor whiteColor];
            [publicView addSubview:backView];
            UIImageView *imageview = [ZCControl createImageViewWithFrame:CGRectMake(5*displaywidth, 12.5*displayheight, 20*displaywidth, 20*displayheight) ImageName:imgAry[i]];
            imageview.contentMode = UIViewContentModeScaleAspectFit;
            [backView addSubview:imageview];
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(35*displaywidth, 12.5*displayheight, 1, 20*displayheight)];
            line.backgroundColor = RGB(204, 204, 204);
            [backView addSubview:line];
            UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(40*displaywidth, 2.5*displayheight, SCREEN_WIDTH-70*displaywidth, 40*displayheight) placeholder:pladerAry[i] passWord:NO leftImageView:nil rightImageView:nil Font:15.0];
            [textfield setValue:RGB(135, 135, 135) forKeyPath:@"_placeholderLabel.textColor"];
            textfield.delegate = self;
            textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
            textfield.textColor = RGB(48, 48, 48);
            textfield.textAlignment = NSTextAlignmentLeft;
            [backView addSubview:textfield];
            if (i == 0)
            {
                nameField = textfield;
            }
            else if(i == 2)
            {
                imageview.hidden = YES;
                line.hidden = YES;
                textfield.frame = CGRectMake(5*displaywidth, 2.5*displayheight, SCREEN_WIDTH-35*displaywidth, 40*displayheight);
                addressField = textfield;
            }
            else if (i == 3)
            {
                textfield.keyboardType = UIKeyboardTypeNumberPad;
                phoneField = textfield;
            }
        }
        else
        {
            UIButton *areaBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, 65*displayheight, 90*displaywidth, 45*displayheight) ImageName:@"my_icon12" Target:self Action:@selector(closeArea) Title:@"选择区域" Font:13.0];
            CGSize imgSize = areaBtn.currentImage.size;
            [areaBtn setTitleColor:RGB(135, 135, 135) forState:UIControlStateNormal];
            areaBtn.backgroundColor = [UIColor whiteColor];
            CGSize titleSize = [areaBtn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:areaBtn.titleLabel.font}];
            UIEdgeInsets titleEdgeInsets = UIEdgeInsetsMake(0, -imgSize.width-5, 0, imgSize.width+5);
            UIEdgeInsets imgEdgeInsets = UIEdgeInsetsMake(0, 5+titleSize.width, 0, -titleSize.width-5);
            areaBtn.titleEdgeInsets = titleEdgeInsets;
            areaBtn.imageEdgeInsets = imgEdgeInsets;
            [publicView addSubview:areaBtn];
            UIView *lines = [[UIView alloc] initWithFrame:CGRectMake(105*displaywidth, 65*displayheight, 5*displaywidth, 45*displayheight)];
            lines.backgroundColor = RGB(245, 245, 245);
            [publicView addSubview:lines];
            areaLab = [ZCControl createLabelWithFrame:CGRectMake(110*displaywidth, 65*displayheight, SCREEN_WIDTH-125*displaywidth, 45*displayheight) Font:15.0 Text:@" 省 - 市 - 区" Color:RGB(135, 135, 135)];
            areaLab.backgroundColor = [UIColor whiteColor];
            [publicView addSubview:areaLab];
        }
    }
    bottomView = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 340*displayheight, SCREEN_WIDTH- 30*displaywidth, 100*displayheight)];
    bottomView.backgroundColor = RGB(245, 245, 245);
    [scrollview addSubview:bottomView];
    NSArray *titAry = @[@"上传门头照",@"上传名片"];
    CGFloat width = ((SCREEN_WIDTH-30*displaywidth)/2-7.5*displaywidth)/2;
    for (int i = 0; i < 2; i++)
    {
        UIView *backV = [[UIView alloc] initWithFrame:CGRectMake((2*width+15*displaywidth)*i, 0, 2*width, 100*displayheight)];
        backV.backgroundColor = [UIColor whiteColor];
        backV.layer.cornerRadius = 5;
        backV.layer.masksToBounds = YES;
        [bottomView addSubview:backV];
        UIImageView *imgV = [ZCControl createImageViewWithFrame:CGRectMake(width-22.5*displayheight+(2*width+15*displaywidth)*i, 11*displayheight, 45*displayheight, 45*displayheight) ImageName:@"my_icon07"];
        imgV.contentMode = UIViewContentModeScaleAspectFill;
        imgV.layer.masksToBounds = YES;
        [bottomView addSubview:imgV];
        UILabel *titlab = [ZCControl createLabelWithFrame:CGRectMake((2*width+15*displaywidth)*i, 70*displayheight, 2*width, 20*displayheight) Font:12.0 Text:titAry[i] Color:RGB(32, 69, 139)];
        titlab.textAlignment = NSTextAlignmentCenter;
        [bottomView addSubview:titlab];
        UIImageView *cardImgview = [ZCControl createImageViewWithFrame:CGRectMake((2*width+15*displaywidth)*i, 0, 2*width, 100*displayheight) ImageName:nil];
        cardImgview.backgroundColor = [UIColor clearColor];
        cardImgview.layer.cornerRadius = 5;
        cardImgview.layer.masksToBounds = YES;
        [bottomView addSubview:cardImgview];
        if (i == 0)
        {
            leftImgView = cardImgview;
        }
        else
        {
            rightImgView = cardImgview;
        }
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, 2*width, 100*displayheight) ImageName:nil Target:self Action:@selector(pushAction:) Title:nil Font:12.0];
        btn.backgroundColor = [UIColor clearColor];
        btn.tag = 200+i;
        [cardImgview addSubview:btn];
    }
    submitBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, 470*displayheight, SCREEN_WIDTH-30*displaywidth, 45*displayheight) ImageName:nil Target:self Action:@selector(submitAction) Title:@"提交" Font:18.0];
    submitBtn.backgroundColor = RGB(255, 153, 20);
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submitBtn.layer.cornerRadius = 5;
    submitBtn.layer.masksToBounds = YES;
    [scrollview addSubview:submitBtn];
    scrollview.contentSize = CGSizeMake(SCREEN_WIDTH, 600*displayheight);
}


//提交
- (void)submitAction
{
    if ([companyField.text isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请输入公司名称" addToView:self.view];
        return;
    }
    if ([nameField.text isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请输入姓名" addToView:self.view];
        return;
    }
    if ([areaLab.text isEqualToString:@" 省 - 市 - 区"])
    {
        [LTools showMBProgressWithText:@"请选择区域" addToView:self.view];
        return;
    }
    if ([addressField.text isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请输入详细地址" addToView:self.view];
        return;
    }
    if (phoneField.text.length != 11)
    {
        [LTools showMBProgressWithText:@"请输入手机号码" addToView:self.view];
        return;
    }
    if (_leftImg == nil)
    {
        [LTools showMBProgressWithText:@"请上传门头照" addToView:self.view];
        return;
    }
    if (_rightImg == nil)
    {
        [LTools showMBProgressWithText:@"请上传名片" addToView:self.view];
        return;
    }
    WEAKSELF;
    NSArray *imgAry = @[_leftImg,_rightImg];
    [HttpTool uploadImageWithPath:@"/file/upload" params:nil thumbName:@"file" ImageAry:imgAry success:^(id json)
     {
         NSArray *imgArray = json[@"data"];
         if (imgArray.count < 2)
         {
             [LTools showMBProgressWithText:@"图片上传出现问题，请重新上传" addToView:weakSelf.view];
             return;
         }
         if ([json server_Getcodecheck])
         {
             NSDictionary *dic = @{@"linkman":nameField.text,
                                   @"chooseAddress":areaLab.text,
                                   @"address":addressField.text,
                                   @"phone":phoneField.text,
                                   @"signboardImg":imgArray[0],
                                   @"cardImg":imgArray[1],
                                   @"companyName":companyField.text,
                                   @"username":nameField.text
                                   };
             [weakSelf requestRecommendSavePhoneParmers:dic];
         }
         else
         {
             [LTools showMBProgressWithText:json[@"msg"] addToView:weakSelf.view];
         }
     } failure:^(NSError *error) {
         
     } progress:^(CGFloat progress) {
         
     }];
}

- (void)requestRecommendSavePhoneParmers:(NSDictionary *)dic
{
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestRecommendSavePhoneParmers:dic Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             
             [LTools showMBProgressWithText:@"提交成功" addToView:sharedDelegate.window];
             [weakSelf.navigationController popViewControllerAnimated:YES];
             
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
     }];
}


//选择区域
- (void)closeArea
{
    [self.view endEditing:YES];
    if (self.pickerView) {
        self.pickerView.hidden = NO;
        return;
    }
    
    self.pickerView = [[JSAddressPickerView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT)];
    [self.pickerView updateAddressAtProvince:@"广东省" city:@"深圳市" town:@"龙岗区"];
    self.pickerView.delegate = self;
    self.pickerView.font = [UIFont boldSystemFontOfSize:14];
    [self.view addSubview:self.pickerView];
}

- (void)JSAddressCancleAction:(id)senter {
    self.pickerView.hidden = YES;
}

- (void)JSAddressPickerRerurnBlockWithProvince:(NSString *)province city:(NSString *)city town:(NSString *)town {
    self.pickerView.hidden = YES;
    //    NSLog(@"%@  %@  %@",province,city,town);
    areaLab.text = [NSString stringWithFormat:@"%@%@%@",province,city,town];
    
    
}

- (void)setPickerView:(JSAddressPickerView *)pickerView {
    if (!_pickerView) {
        
    }
    _pickerView = pickerView;
}

//上传照片
- (void)pushAction:(UIButton *)btn
{
    [self.view endEditing:YES];
    _phoneType = btn.tag-200;
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //拍照
    WEAKSELF;
    [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"拍照");
        [weakSelf takePhoto];
        
    }]];
    
    //从相册中选取
    [alertVC addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        HYLog(@"从相册中选取");
        [weakSelf choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"取消");
        [weakSelf dismissViewControllerAnimated:NO completion:nil];
    }]];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

-(void)takePhoto
{
    //    判断是否打开相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您尚未开启相机权限，请去系统设置界面打开相机权限！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
        
        
    }
    else
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            
        }
        
    }
}

// 滑动的时候 searchBar 回收键盘

- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
    [self.view endEditing:YES];
    
}

-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate =self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing =YES;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    if (_phoneType == 0)
    {
        _leftImg = image;
        leftImgView.image = image;
    }
    else
    {
        _rightImg = image;
        rightImgView.image = image;
    }
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)jianpanhuishou:(NSNotification *)notification
{
    scrollview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT);
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == phoneField)
    {
        scrollview.frame = CGRectMake(0, -130*displayheight, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT);

    }
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
